/*
 * @: 
 * @Version: 1.0
 * @Autor: ziwei
 * @Date: 2021-11-02 10:36:31
 * @LastEditors: ziwei
 * @LastEditTime: 2021-11-15 22:36:46
 */
//指令生成器
import {put,take,select, takeEvery,call,cps,all,fork,cancel} from '../redux-saga/effects'
import * as actionTypes from './action-types'
//如何取消已经开始的任务
// function *watcherSaga() {
//   yield take(actionTypes.ASYNC_ADD)
//   yield workerSaga();
// }

// function *workerSaga() {
//   yield put({type:actionTypes.ADD})
// }
function * workAdd(){
  while(true){
    yield delay(1000);
    yield put({type:actionTypes.ADD})
  }
}

function * watcherAdd(){
  //开启新则子进程
  const task = yield fork(workAdd);
  console.log(task);//{cancel} cancel()
  //等待动作STOP_ADD
  yield take(actionTypes.STOP_ADD)
  yield cancel(task)
}

//必须要用 watcher和worker可有可无没有也可以，有的话更清晰
export default function * rootSaga() {
  console.log('开始执行rootSaga');
  //take等待有人向仓库派发action.type=ASYNC_ADD的动作，如果等不到就卡在这不动不往后执行
  //take和put都是函数 用来生成指令对象
  // yield take(actionTypes.ASYNC_ADD)
  // console.log('after ASYNC_ADD');
  // //put向仓库发一个action动作
  // yield put({type:actionTypes.ADD})
  // console.log('after after ADD');
  for(let i=0;i<3;i++){
    const oldNumber = yield select(state=>state.number);
    console.log('oldNumber',oldNumber);
    const action = yield take(actionTypes.ASYNC_ADD);
    console.log('action',action);
    yield put({type:actionTypes.ADD});
    const newNumber = yield select(state=>state.number);
    console.log('newNumber',oldNumber);
  }
  console.log('已经到达最大值了');
}